import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
	{
		path: '/',
		redirect: '/home'
	},
	{
		path: '/home',
		name: 'home',
		meta: {
			title: '首页'
		},
		component: () => import('@/views/home/index.vue')
	},
	{
		path: '/todos/:id',
		name: 'todos',
		component: () => import('@/views/todos/index'),
		props: true
	},
	{
		path: '/login',
		component: () => import('@/views/login')
	}
]

const router = createRouter({
	history: createWebHashHistory(),
	routes
})

router.beforeEach((to, from, next) => {
	// console.log(to, from);
	to.meta.title && (document.title = to.meta.title as string)
	if (to.name === 'todos') {
		if (to.query.name) document.title = to.query.name as string
		to.meta.transitionName = 'slide-in'
	}
	if (from.name === 'todos') {
		to.meta.transitionName = 'slide-out'
	}

	if (to.path !== '/login' && !localStorage.getItem('token')) {
		next('/login')
		return
	}

	next()
})

export default router
